package com.block.account.service.impl;

import cn.hutool.core.util.NumberUtil;
import com.block.account.model.dto.ChangeAmountDTO;
import com.block.account.model.result.ChangeAmountResult;
import com.block.account.service.IAccountCommonService;
import com.block.account.service.IAccountProductInfoHisService;
import com.block.db.entity.AccountMerchantInfo;
import com.block.db.entity.AccountProductInfo;
import com.block.db.mapper.AccountProductInfoMapper;
import com.block.account.service.IAccountProductInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * <p>
 * 产品账户信息 服务实现类
 * </p>
 *
 * @author 
 * @since 2023-08-26
 */
@Service
public class AccountProductInfoServiceImpl extends ServiceImpl<AccountProductInfoMapper, AccountProductInfo> implements IAccountProductInfoService, IAccountCommonService {

    @Autowired
    IAccountProductInfoHisService accountProductInfoHisService;

    @Override
    @Transactional
    public ChangeAmountResult changeAmount(ChangeAmountDTO changeAmountDTO) {

        AccountProductInfo accountProductInfo = this.baseMapper.getEntityByAccountIdLock(changeAmountDTO.getAccountId());
        // 修改账户余额
        BigDecimal totalAmount = NumberUtil.add(accountProductInfo.getTotalAmount(), changeAmountDTO.getChangeAmount());

        ChangeAmountResult changeAmountResult = new ChangeAmountResult();
        changeAmountResult.setSuccess(false);
        changeAmountResult.setNoticeFlag(false);

        /**
         * 修改金额
         */
        AccountProductInfo updateEntity = new AccountProductInfo();
        updateEntity.setProductId(accountProductInfo.getProductId());
        updateEntity.setTotalAmount(totalAmount);
        updateEntity.setUpdateTime(LocalDateTime.now());
        boolean updateRes = this.updateById(updateEntity);
        if (!updateRes){
            return changeAmountResult;
        }

        boolean saveHis = accountProductInfoHisService.saveAccountHis(totalAmount, accountProductInfo, changeAmountDTO);
        if (!saveHis){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return changeAmountResult;
        }

        changeAmountResult.setSuccess(true);
        return changeAmountResult;
    }

}
